package com.edu.html.controller;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;
import com.edu.common.controller.BaseController;
import com.edu.html.pojo.User;

@Controller
@RequestMapping("/user")
public class UserController extends BaseController {
	
	private static final Logger logger = Logger.getLogger(UserController.class);
	
	@RequestMapping("/login.shtml") // url
	public String login(User user, Model model) {
		logger.info("Msg:登录请求数据："+JSON.toJSON(user));
		String info = loginUser(user);
		if (!"SUCC".equals(info)) {
			model.addAttribute("failMsg", info);
			return "/login";
		} else {
			return "redirect:/html/welcome.shtml";// 返回的页面
		}
	}

	@RequestMapping("/logout.shtml")
	public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			try {
				subject.logout();
			} catch (Exception ex) {
			}
		}
		response.sendRedirect("/edu/html/login.shtml");
	}
	
	@RequestMapping("/register.shtml")
	public String register(User user, Model model){
		logger.info("Msg:注册请求数据："+JSON.toJSON(user));
		if(!validateRegister(user)){
			model.addAttribute("failMsg", "参数不完整");
		}else{
			model.addAttribute("failMsg", "注册成功，请重新登录");
		}
		return "/login";
	}
	
	private boolean validateRegister(User user){
		if(user == null){
			return false;
		}
		if(StringUtils.isEmpty(user.getUsername()) || StringUtils.isEmpty(user.getPassword())){
			return false;
		}
		String MD5 = "md5";  
		int retryCount = 5;  
	    String salt = new SecureRandomNumberGenerator().nextBytes().toHex();  
	    SimpleHash hash = new SimpleHash(MD5, user.getPassword(),user.getUsername() + salt, retryCount);  
	    String encodedPassword = hash.toHex();  
	    user.setSalt(salt);
	    user.setPassword(encodedPassword);
	    return true;
	}

	private String loginUser(User user) {
		if (isRelogin(user)){
			return "SUCC"; // 如果已经登陆，无需重新登录
		}
		return shiroLogin(user); // 调用shiro的登陆验证
	}

	private String shiroLogin(User user) {
		// 组装token，包括客户公司名称、简称、客户编号、用户名称；密码
		UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword().toCharArray(), null);
		token.setRememberMe(true);
		// shiro登陆验证
		try {
			SecurityUtils.getSubject().login(token);
		} catch (UnknownAccountException ex) {
			return "用户不存在或者密码错误！";
		} catch (IncorrectCredentialsException ex) {
			return "用户不存在或者密码错误！";
		} catch (AuthenticationException ex) {
			return ex.getMessage(); // 自定义报错信息
		} catch (Exception ex) {
			ex.printStackTrace();
			return "内部错误，请重试！";
		}
		return "SUCC";
	}

	private boolean isRelogin(User user) {
		Subject us = SecurityUtils.getSubject();
		if (us.isAuthenticated()) {
			return true; // 参数未改变，无需重新登录，默认为已经登录成功
		}
		return false; // 需要重新登陆
	}

}
